package com.ojoin.trade.t0loan_core.web.monitor;

import java.util.Collection;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 15-10-8
 * Time: 下午2:37
 * To change this template use File | Settings | File Templates.
 */
public class ThreadTrace {

    private ConcurrentHashMap<Thread, ThreadEntry> hThreadEntry = new ConcurrentHashMap<Thread, ThreadEntry>();

    private static ThreadTrace m_inst;

    public static synchronized ThreadTrace getInstance() {
        if (m_inst == null) {
            m_inst = new ThreadTrace();
        }
        return m_inst;
    }

    public void startThreadMonitor(String method,String remoteaddr,String url) {
        Thread t = Thread.currentThread();
        ThreadEntry entry = hThreadEntry.get(t);
        if (entry == null) {
            entry = new ThreadEntry();
            entry.setBegintime(System.currentTimeMillis());
            String tName = t.getName();
            entry.setName(tName == null ? "service" : tName);
            entry.setId(t.getId());
            entry.setRemoteaddr(remoteaddr);
            entry.setMethod(method);
            entry.setUrl(url);
            hThreadEntry.putIfAbsent(t, entry);
        }



    }

    public void endMonitor() {
        Thread t = Thread.currentThread();
        ThreadEntry entry = hThreadEntry.get(t);
        hThreadEntry.remove(t);
        if (entry == null)
            return;
        entry.initcosttime();
    }
    synchronized public ThreadEntry[] getAllThreadInfo() {
        hThreadEntry.remove(Thread.currentThread());
        preWorkWhenRemoteCall();
        Collection<ThreadEntry> collection = hThreadEntry.values();
        if (collection.size() == 0) {
            return null;
        }
        return (ThreadEntry[]) collection.toArray(new ThreadEntry[collection
                .size()]);
    }

    private void preWorkWhenRemoteCall() {
        Enumeration<Thread> threads = hThreadEntry.keys();
        Thread t = null;
        while (threads.hasMoreElements()) {
            t = threads.nextElement();
            ThreadEntry threadEntry = hThreadEntry.get(t);
            if (threadEntry == null)
                continue;
            String tstatus = t.getState().name();
            if (tstatus != null && tstatus.equalsIgnoreCase("TERMINATED")) {
                hThreadEntry.remove(t);
                continue;
            }
            threadEntry.setStackTrace0(t.getStackTrace());
            threadEntry.initcosttime();
        }
    }
}
